<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="700px"
    align-center
    draggable
    class="publishDialog"
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      style="width: 90%"
    >
      <el-form-item label="终端类型" prop="terminalType">
        <el-select
          v-if="!props.isReadonly"
          style="width: 100%"
          v-model="formData.terminalType"
          placeholder="请选择终端类型"
          clearable
        >
          <el-option key="10" label="Android" value="10" />
          <!--          <el-option-->
          <!--              key="10"-->
          <!--              label="IOS"-->
          <!--              value="20"-->
          <!--          />-->
        </el-select>
        <span v-else>{{
          formData.terminalType == "10" ? "Android" : "IOS"
        }}</span>
      </el-form-item>

      <el-form-item label="版本名称" prop="versionName">
        <el-input
          v-if="!props.isReadonly && formData.terminalType == 20"
          v-model="formData.versionName"
          placeholder="请输入版本名称"
          clearable
        />
        <span v-else>{{ formData.versionName }}</span>
      </el-form-item>

      <el-form-item
        label="版本号"
        prop="versionCode"
        v-if="formData.terminalType == 10"
      >
        <span>{{ formData.versionCode }}</span>
      </el-form-item>

      <el-form-item
        label="安卓apk包上传"
        prop="versionCode"
        v-if="formData.terminalType == 10 && !props.isReadonly"
      >
        <el-upload
          class="upload-demo"
          drag
          :http-request="uploadFileApk"
          multiple
          style="width: 100%"
        >
          <el-icon class="el-icon--upload">
            <i-ep-upload-filled />
            <!--            <upload-filled/>-->
          </el-icon>
          <div class="el-upload__text">将文件拖至此处或<em>点击上传</em></div>
          <template #tip> </template>
        </el-upload>
      </el-form-item>

      <el-form-item label="版本信息" prop="versionInfo">
        <el-input
          v-if="!props.isReadonly"
          type="textarea"
          v-model="formData.versionInfo"
          placeholder="请输入版本信息"
          clearable
        />

        <span v-else>{{ formData.versionInfo }}</span>
      </el-form-item>
      <!--      <el-form-item label="版本下载链接" prop="appUrl">-->
      <!--        <el-input v-if="!props.isReadonly" v-model="formData.appUrl" placeholder="请输入版本下载链接" clearable/>-->

      <!--        <span v-else>{{ formData.appUrl }}</span>-->
      <!--      </el-form-item>-->
      <el-form-item label="是否启用" prop="enabled">
        <el-select
          v-if="!props.isReadonly"
          style="width: 100%"
          v-model="formData.enabled"
          placeholder="请选择是否启用"
          clearable
        >
          <el-option
            v-for="item in dictionaryStore.filterDictList('Enabled')"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <span v-else>{{
          dictionaryStore.filterDictName("Enabled", formData.enabled)
        }}</span>
      </el-form-item>
      <!-- <el-form-item label="是否强制升级" prop="forceUpdate">
        <el-select v-if="!props.isReadonly" style="width: 100%" v-model="formData.forceUpdate"
                   placeholder="请选择是否强制升级"
                   clearable>
          <el-option
              v-for="item in dictionaryStore.filterDictList('Enabled')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
        <span v-else>{{ dictionaryStore.filterDictName('Enabled', formData.forceUpdate) }}</span>
      </el-form-item> -->
      <!--      <el-form-item label="生效时间" prop="effectTime">-->
      <!--        <el-input v-if="!props.isReadonly" v-model="formData.effectTime" placeholder="请输入生效时间" clearable/>-->

      <!--        <span v-else>{{ formData.effectTime }}</span>-->
      <!--      </el-form-item>-->
      <el-form-item label="备注" prop="remark">
        <el-input
          v-if="!props.isReadonly"
          type="textarea"
          v-model="formData.remark"
          placeholder="请输入备注"
          clearable
        />

        <span v-else>{{ formData.remark }}</span>
      </el-form-item>
      <!--      <el-form-item label="首页更新提示：10不显示20同一用户同一日显示一次30无限制" prop="updateTips">-->
      <!--        <el-input v-if="!props.isReadonly" v-model="formData.updateTips"-->
      <!--                  placeholder="请输入首页更新提示：10不显示20同一用户同一日显示一次30无限制" clearable/>-->

      <!--        <span v-else>{{ formData.updateTips }}</span>-->
      <!--      </el-form-item>-->
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { UploadRequestOptions, ElLoading } from "element-plus"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "SYSAPPVERSIONADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

const rules = reactive({
  versionCode: [],
  versionName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  versionInfo: [
    { min: 1, max: 500, message: "长度在 1 到 500 个字符", trigger: "blur" },
  ],
  appUrl: [
    { min: 1, max: 500, message: "长度在 1 到 500 个字符", trigger: "blur" },
  ],
  enabled: [
    { min: 1, max: 2, message: "长度在 1 到 2 个字符", trigger: "blur" },
  ],
  remark: [
    { min: 1, max: 10, message: "长度在 1 到 10 个字符", trigger: "blur" },
  ],
  forceUpdate: [
    { min: 1, max: 2, message: "长度在 1 到 2 个字符", trigger: "blur" },
  ],
  terminalType: [
    { min: 1, max: 2, message: "长度在 1 到 2 个字符", trigger: "blur" },
  ],
  effectTime: [],
  updateTips: [
    { min: 1, max: 2, message: "长度在 1 到 2 个字符", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  versionCode: "",
  totalSize: "",
  versionName: "",
  versionInfo: "",
  appUrl: "",
  enabled: "1",
  remark: "",
  forceUpdate: "1",
  terminalType: "10",
  effectTime: "",
  deleted: "",
  updateTips: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        versionCode,
        totalSize,
        versionName,
        versionInfo,
        appUrl,
        enabled,
        remark,
        forceUpdate,
        terminalType,
        effectTime,
        deleted,
        updateTips,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
      } = newVal;
      Object.assign(formData, {
        id,
        versionCode,
        totalSize,
        versionName,
        versionInfo,
        appUrl,
        enabled,
        remark,
        forceUpdate,
        terminalType,
        effectTime,
        deleted,
        updateTips,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.versionCode = "";
  formData.totalSize = "";
  formData.versionName = "";
  formData.versionInfo = "";
  formData.appUrl = "";
  formData.enabled = "1";
  formData.remark = "";
  formData.forceUpdate = "1";
  formData.terminalType = "10";
  formData.effectTime = "";
  formData.deleted = "";
  formData.updateTips = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
}

const loading = ref(false);

/** APP版本表保存提交 */
function handleSubmit() {
  if (!formData.versionName) {
    if (formData.terminalType == 10) {
      ElMessage.error(`请填上传apk安装包`);
      return;
    }
  }
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/system/sysappversion/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

// 导入excel
const uploadApi = "/system/sysappversion/upload";
const excelBox = ref(false);
const uploadBtn = ref(false);
const uploadFile = ref("");
const fileName = ref("");

function excelBoxOpen() {
  excelBox.value = true;
}

function getfilepath(e: any) {
  const file = e.target.files[0];
  fileName.value = file.name;
  uploadFile.value = file;
  uploadBtn.value = false;
}

function uploadFileApk(options: UploadRequestOptions) {
  let loadingInstance = ElLoading.service({
    target: ".publishDialog",
    lock: true,
    text: "apk上传中, 请稍后···",
  });
  let formdata = new FormData();
  formdata.append("file", options.file);
  let config = { headers: { "Content-Type": "multipart/form-data" } };
  request
    .post(uploadApi, formdata, config)
    .then((res) => {
      if (res.code == 200) {
        formData.versionCode = res.data.versionCode;
        formData.appUrl = res.data.src;
        formData.totalSize = res.data.totalSize;
        formData.versionName = res.data.versionName;
      } else {
      }
      loadingInstance.close();
    })
    .catch((error) => {
      console.log(error);
      loadingInstance.close();
    });
}
</script>
